<?php


namespace App\Models\CacheModel;


use app\aliyun\controller\AliyunFilterWord;
use App\Models\CacheModel\lucky\AppUserAdornInfo;
use App\Models\CacheModel\zl1_relation\Zl1AstrCommunityArticle;
use App\Models\CacheModel\zl2\Zl2AstrFortuneArticle;
use App\Models\CacheModel\zlcr2\Zlcr2UserQuestion;
use app\common\lib\ConfigManage;
use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use App\Models\Api\BaseCache;
use App\Models\Api\MessageCenter;
use App\Models\Api\User;
use Exception;
use think\Cache;
use think\Log;
use AstroTool\Cache\CacheManage;

class ArticleComment extends BaseCache
{
    protected $table = 'wechatadmin.system_article_comment';
    public $cacheModel = 'content.comment';
    // 问答提问者 是否匿名
    public $isAnonymity = false;
    // 问答提问者 匿名头像和昵称
    public $anonymityNickname = '匿名用户';
    public $anonymityAvatar = '/test/question_answer/anonymity1.png';

    /**
     * 评论删除
     * @param int $uid
     * @param int $id 评论id
     * @param int $type 1=>星文，2=>女神动态，3=>女神专区 必传
     * @return bool
     */
    public function commentDel($uid, $id)
    {
        try
        {
            //获取评论信息
            $comment = current($this->batchGetInfo([$id], ['type', 'aid', 'reply', 'uid']));
            if ($comment)
            {
                if ($comment['uid'] != $uid)
                {
                    throw new ApiException('数据不存在');
                }
                $reply_num = $comment['reply'] + 1;//删除当前评论，判断是否有回复
                $this->where(['id' => $id, 'uid' => $uid])->update(['status' => -1]);
                //更新对应文章的评论列表缓存
                $this->listDataDel($comment['type'], [$id], $comment['aid']);
                //更新问答讨论列表
                if ((int)$comment['type'] === 4)
                {
                    //更新对应用户的评论列表缓存
                    CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('question_user_list', $comment['uid'])->rmCache('question_user_list');

                    $questionModel = new Zlcr2UserQuestion();
                    $questionInfo = $questionModel->getInfoById($comment['aid'], ['uid']);
                    if ($questionInfo['uid'] == $uid)
                    {   // 提问者删除自己的评论
                        $this->delQuestionAnswerRecommentIdCache($comment['aid'], 4);
                    }
                    // 删除点赞+回复 缓存
                    CacheManage::getInstance()->setCacheConfig($this->cacheModel, 'question_answer_' . $comment['aid'])->setListKeyType('comment_good')->delJudge($id);
                }
                //删除评论详情缓存
                CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->rmCache();
                // 新增文章|动态|话题 评论数 互动数（更新文章评论数）
                $cacheKey = $comment['type'] == 1 ? 'comment' : 'comment_num';
                $this->commentOrgoodAdd($comment['type'], $comment['aid'], $cacheKey, -$reply_num);
                //获取评论的话题信息，删除话题缓存更新热门评论
                if ($comment['type'] == 3)
                {
                    $areaModel = new GoddessArea();
                    $article = current($areaModel->batchGetThemeInfo([$comment['aid']], ['good_max_comment_id']));
                    if ($article)
                    {
                        //若当前评论是话题点赞最高的或者含有女神回复信息则清除话题详情缓存
                        if ($article['good_max_comment_id'] == $id || $comment['goddess_reply_id'])
                        {
                            CacheManage::getInstance()->setCacheConfig($areaModel->cacheModel)->rmCache();
                        }
                    }
                }
                //将所属女神回复状态改为删除
                $replyModel = new ArticleCommentReply();
                $goddessReplyIds = $replyModel->getGoddessReplyIds($id);
                if ($goddessReplyIds)
                {
                    $replyModel->where(['id' => $goddessReplyIds])->update(['status' => -1]);
                }
            }
        }
        catch
        (Exception $e)
        {
            return false;
        }
        return true;
    }

    /**
     * 评论添加
     * @param array $userInfo 用户信息
     * @param array $data
     * @param bool $complainSwitch 内容申诉开关
     * @return array
     * @throws ApiException
     * @throws Exception
     */
    public function commentAdd(array $userInfo, array $data = [], bool $complainSwitch = true)
    {
        $typeName = $data['type'] === 4 ? '讨论' : '评论';
        if (Util::commentCheck($userInfo['id'], $data))
        {   // 重复评论验证
            return [
                'status' => false,
                'msg' => '重复' . $typeName . '过快'
            ];
        }
        $data['create_time'] = request()->time();

        //若内容有违规且超过配置的相似比例，则进行隐藏不显示，将标签存入库中
        $res = AliyunFilterWord::checkText($data['content'], 'article_comment');
        if ($res)
        {
            $data['check_status'] = 1;
            $data['illegal_type'] = $res['label_type'];
            $data['illegal_level'] = $res['level'];
            $data['data_id'] = $res['data_id'];
            $data['status'] = -1;
        }
        //旧版本违规处理
        if (!$complainSwitch && $res)
        {
            return [
                'status' => false,
                'msg' => '当前' . $typeName . '中有敏感词'
            ];
        }

        try
        {
            $cacheKey = 'comment_num';
            //获取对应的内容信息
            switch ($data['type'])
            {
                case 1:
                    $article = current((new Article())->batchGetInfo([$data['aid']], ['id', 'title']));
                    $cacheKey = 'comment';
                    break;
                case 2:
                    $article = (new ZlGoddessState())->getInfoById($data['aid'], ['title']);
                    break;
                case 3:
                    $article = current((new GoddessArea())->batchGetThemeInfo([$data['aid']], ['id', 'title', 'reply_avatars']));
                    break;
                case 4:
                    $article = (new Zlcr2UserQuestion())->getInfoById($data['aid'], ['question']);
                    $article['title'] = $article['question'];
                    break;
                case 5:
                    $article = (new Zl1AstrCommunityArticle())->getInfoById($data['aid'], ['id', 'title']);
                    break;
                case 6:
                    $article = (new Zl2AstrFortuneArticle())->getInfoById($data['aid'], ['id', 'title']);
                    break;
                default:
                    $article = [];
            }
            if ($article)
            {
                $commentId = $this->insertGetId($data);
                //若当前评论无违规则进行缓存处理
                if (!$res)
                {
                    // 评论列表信息 当前评论ID
                    $this->listDataAdd($data['type'], [$commentId => $commentId], $data['aid']);
                    //更新问答讨论列表
                    if ((int)$data['type'] === 4)
                    {
                        // 添加至问答-蹭看用户列表
                        CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('question_user_list', $userInfo['id'])->listAdd([$data['aid'] => $commentId], 0, 'question_user_list');
                    }
                    if ($data['type'] == 3 && $userInfo['avatar'])
                    {   // 互动头像添加
                        (new GoddessArea())->interactionAvatars($data['aid'], $userInfo['avatar'], $article);
                    }
                    if (in_array($data['type'], [1, 2, 3], true))
                    {
                        // 新增文章|动态|话题 评论数 互动数
                        $this->commentOrgoodAdd($data['type'], $data['aid'], $cacheKey, 1);
                    }
                }
            } else
            {
                return [
                    'status' => false,
                    'msg' => '请求异常'
                ];
            }
        }
        catch (Exception $e)
        {
            return [
                'status' => false,
                'msg' => '服务异常，请稍后再试'
            ];
        }
        if ($res)
        {
            //文章评论违规发送消息
            if ($commentId && in_array($data['type'], [1, 2, 3], false))
            {
                $messageData = [
                    'status' => 0,
                    'is_read' => 0,
                    'range' => $userInfo['id'],
                    'type' => 1,
                    'article_comment_id' => $commentId,
                    'article_comment_reply_id' => 0,
                    'reid' => 0,
                    'cid' => 0,
                    'title' => $typeName . '内容违禁处理',
                    'content' => '亲爱的用户，您在《' . $article['title'] . '》中的' . $typeName . '[REPLACE]由于涉嫌违禁词汇言论（' . $res['label'] . '）已做隐藏删除处理，若您有异议点击内容申诉官方人工二次审核',
                    'link' => '',
                    'target' => '',
                    'create_time' => time()
                ];
                //添加消息
                (new MessageCenter())->pushMessage($userInfo['id'], $messageData);
                throw new ApiException('小准准检测到您的' . $typeName . '涉嫌违规' . PHP_EOL . '已做处理，点击查看详情', 200, 201);
            }
            throw new ApiException('您的评论有敏感词！', 200, 0);
        }
        return [
            'status' => true,
            'id' => $commentId
        ];
    }

    /**
     * 文章评论数|点赞数|互动数增加 （收藏|已读不增加互动数）
     * @param int $type 1=>星文，2=>女神动态，3=>女神专区 必传
     * @param int $aid 文章ID | 动态ID | 话题ID
     * @param string $key 字段key   good_num(good)|comment_num(comment)|collect_num(collect)|read_num(read)
     * @param int $inc 步数（1 / -1）
     * @throws Exception
     */
    public function commentOrgoodAdd(int $type, int $aid, string $key, int $inc)
    {
        $cacheKey = [
            1 => 'content.article_info',
            2 => 'goddesss_state.state',
            3 => 'goddess_area.theme',
        ];
        $updateDb = false; // 是否更新数据库y6

        if (isset($cacheKey[$type]))
        {
            $cache = CacheManage::getInstance()->setCacheConfig($cacheKey[$type], $aid);
            // 基数记录增加   用于减少更新数据库频率
            $addNum = $cache->setCacheKeyDetail('inc_base_num', $aid)->setCacheInc($key, 'inc_base_num', $inc);
            if ($addNum > ($cache->cacheKey['base_max'] ?? 100))
            {   // 更新数据库记录
                $updateDb = true;
                // 删除记录
                $cache->rmCache('inc_base_num');
            }

            if ($cache->existsKey('details'))
            { // 缓存存在 则更新缓存 点赞数|评论数 和 互动数
                if ($updateDb)
                {   // 更新入库
                    switch ($type)
                    {
                        case 1:
                            $data = $cache->getCache(['comment', 'good', 'collect', 'read']);
                            $data[$key]++;
                            array_map(function ($val)
                            {
                                return (int)$val;
                            }, $data);
                            // 更新缓存
                            $cache->setCache($data);
                            // 更新数据库
                            (new Article())->where('id', $aid)->update($data);
                            break;
                        case 2:
                            $data = $cache->getCache(['comment_num', 'good_num', 'collect_num', 'read_num']);
                            $data[$key]++;
                            array_map(function ($val)
                            {
                                return (int)$val;
                            }, $data);
                            // 更新缓存
                            $cache->setCache($data);
                            // 更新数据库
                            (new ZlGoddessState())->where('id', $aid)->update($data);
                            break;
                        case 3:
                            $data = $cache->getCache(['comment_num', 'good_num', 'collect_num', 'interaction_num', 'read_num']);
                            $data[$key]++;
                            if (!in_array($key, ['collect_num', 'read_num']))
                            {   // 收藏 和阅读除外
                                $data['interaction_num']++;
                            }
                            array_map(function ($val)
                            {
                                return (int)$val;
                            }, $data);
                            // 更新缓存
                            $cache->setCache($data);
                            // 更新数据库
                            (new GoddessArea())->where('id', $aid)->update($data);
                            break;
                    }

                } else
                {
                    switch ($type)
                    {
                        case 1:
                        case 2:
                            // 评论数|点赞数|收藏数增加|已读数
                            $cache->setCacheInc($key, 'details', $inc);
                            break;
                        case 3:
                            // 评论数|点赞数|收藏数增加
                            $cache->setCacheInc($key, 'details', $inc);
                            if (!in_array($key, ['collect_num', 'read_num']))
                            {   // 互动数增加 【收藏和阅读不增加互动数】
                                $cache->setCacheInc('interaction_num', 'details', $inc);
                            }
                            break;
                    }
                }
            }
            // 缓存失效 暂时不做更新操作
        }
    }

    /**
     * 获取评论信息 列表信息
     * @param int|null $uid
     * @param int $type 1=>星文，2=>女神动态，3=>女神专区 4=>问答 5=>星座讨论 6=>星运内容动态
     * @param $aid 文章ID | 动态ID | 话题ID
     * @param int $isOld 是否是新版本 1=>旧版本2.0.0之前 2=>新版本2.0.0之后
     * @param int $page
     * @param int $limit
     * @return array
     * @throws \app\common\lib\exception\ApiException
     * @throws Exception
     */
    public function getPageCommentList($uid, int $type, $aid, int $isOld = 2, int $page = 1, int $limit = 10): array
    {
        if ($type === 4)
        {
            $thisPageData = $this->getQuestionAnswerCommentPageIds($aid, $type, $page, $limit);
        } else
        {
            $thisPageData = $this->getCommentPageIds($aid, $type, $page, $limit);
        }

        if ($thisPageData['data'])
        {
            // 通过ids 批量获取话题详情
            $commentDatas = $this->batchGetInfo($thisPageData['data']);
            // 重组详情数据
            $thisPageData['data'] = $this->commentDataReset($uid, $thisPageData['data'], $commentDatas, $type, $isOld);
        }

        return $thisPageData;
    }

    /**
     * 获取分页数据ID
     * @param string $aid 文章ID | 动态ID | 话题ID
     * @param int $type 1=>星文评论，2=>女神动态评论，3=>女神专区评论 4=>问答 5=>星座讨论 6=>星运内容动态
     * @param int $page
     * @param int $limit
     * @return array|mixed
     * @throws Exception
     */
    public function getCommentPageIds(string $aid, int $type, int $page, int $limit)
    {
        $officialUser = (new \App\Models\CacheModel\ZlAdminVip())->getVipInfo(4); // 官方用户
        $ids = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $type)->setListKeyType($aid)
            ->setSort('desc')->ZsGetIocData('list', function () use ($aid, $type, $officialUser)
            {
                $data = $this->where(['aid' => $aid, 'type' => $type, 'status' => 0])->column('is_top,has_goddess_reply,uid', 'id');
                $ids = [];

                foreach ($data as $id => $value)
                {
                    $isOfficialUser = in_array($value['uid'], $officialUser, false) ? 1 : 0;
                    if ($isOfficialUser && $value['is_top'])
                    { // 如果是小助理并且置顶了 排序权重 比女神回复未置顶 大 // 权重单独设置 女神回复(置顶) > 小助理(置顶) >女神回复 >  置顶 > 小助理 > 普通回复
                        $ids[$id] = 1050000000 + $id;
                    } else
                    {
                        //判断评论是否置顶
                        $ids[$id] = ($value['has_goddess_reply'] * 1000000000) + ($value['is_top'] * 100000000) + ($isOfficialUser * 10000000) + $id;
                    }
                }
                arsort($ids);
                return $ids;
            });

        $themeIds = [];
        $total = count($ids); // 总话题数
        $lastPage = $page < 1 ? 1 : (int)ceil($total / $limit); // 总页数

        if ($page < 1)
        { // 获取所有ID
            $themeIds = $ids;
        } elseif ($page > 0 && $page <= $lastPage)
        { // 第分页IDS
            $star = ($page - 1) * $limit;
            $themeIds = array_slice($ids, $star, $limit);
        }

        return [
            'total' => $total,// 记录总数
            'per_page' => $page < 1 ? -1 : $limit,// 每页多少条
            'current_page' => $page,// 当前页数
            'last_page' => $lastPage,// 总页数
            'data' => $themeIds,
        ];
    }

    /**
     * 获取 问答 分页数据ID
     * @param string $aid 文章ID | 动态ID | 话题ID
     * @param int $type 1=>星文评论，2=>女神动态评论，3=>女神专区评论 4=>问答
     * @param int $page
     * @param int $limit
     * @return array|mixed
     * @throws Exception
     */
    public function getQuestionAnswerCommentPageIds(string $aid, int $type, int $page, int $limit)
    {
        $officialUser = (new \App\Models\CacheModel\ZlAdminVip())->getVipInfo(4); // 官方用户
        $ids = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $type)->setListKeyType($aid)
            ->setSort('desc')->ZsGetIocData('list', function () use ($aid, $type, $officialUser)
            {
                $data = $this->where(['aid' => $aid, 'type' => $type, 'status' => 0])->column('is_top,has_goddess_reply,uid', 'id');
                $ids = [];

                foreach ($data as $id => $value)
                {
                    $isOfficialUser = in_array($value['uid'], $officialUser, false) ? 1 : 0;
                    if ($isOfficialUser && $value['is_top'])
                    { // 如果是小助理并且置顶了 排序权重 比女神回复未置顶 大 // 权重单独设置 女神回复(置顶) > 小助理(置顶) >女神回复 >  置顶 > 小助理 > 普通回复
                        $ids[$id] = 1050000000 + $id;
                    } else
                    {
                        //判断评论是否置顶
                        $ids[$id] = ($value['has_goddess_reply'] * 1000000000) + ($value['is_top'] * 100000000) + ($isOfficialUser * 10000000) + $id;
                    }
                }
                arsort($ids);
                return $ids;
            });

        $questionInfo = (new Zlcr2UserQuestion())->getInfoById($aid, ['uid']);
        // 获取 提问者 讨论的 最近的一条
        $id1 = $this->getQuestionAnswerRecommentId($aid, 4, $questionInfo['uid'], 1);  // 数组格式
        // 获取点赞 + 回复最多的3条
        $recommentIds = $this->getCommentAndGoodMaxLimit($aid, 4);
        $recommentIds = array_diff($recommentIds, $id1);

        $id1 = array_merge($id1, $recommentIds);

        $ids = array_diff($ids, $id1);

        $resIds = array_merge($id1, $ids);

        $themeIds = [];
        $total = count($resIds); // 总话题数
        $lastPage = $page < 1 ? 1 : (int)ceil($total / $limit); // 总页数

        if ($page < 1)
        { // 获取所有ID
            $themeIds = $resIds;
        } elseif ($page > 0 && $page <= $lastPage)
        { // 第分页IDS
            $star = ($page - 1) * $limit;
            $themeIds = array_slice($resIds, $star, $limit);
        }

        return [
            'total' => $total,// 记录总数
            'per_page' => $page < 1 ? -1 : $limit,// 每页多少条
            'current_page' => $page,// 当前页数
            'last_page' => $lastPage,// 总页数
            'data' => $themeIds,
        ];
    }

    /**
     * 获取用户评论ids
     * @param string $uid
     * @return array
     * @throws \Exception
     */
    public function getUserCommentIds(string $uid): array
    {
        $page = input('page/d', 1);
        return CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel)
            ->setCacheKeyDetail('question_user_list', $uid)
            ->setSort('desc')
            ->setPage($page)
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc') use ($uid)
            {
                try
                {
                    $where = ['uid' => $uid, 'status' => ['neq', -1], 'type' => 4];
                    $data = $this->where($where)->order('id', 'DESC')->column('id', 'aid');
                    $resData = [];
                    foreach ($data as $aid => $id)
                    {
                        $resData[$aid] = ['id' => $id];
                    }

                    return $resData;
                }
                catch (\Exception $e)
                {
                    return [];
                }
            }, 'id', 0, 'question_user_list');
    }

    /**
     * 批量获取评论详情
     * @param array $ids
     * @param array $filed
     * @return array
     * @throws Exception
     */
    public function batchGetInfo(array $ids, array $filed = []): array
    {
        $commentDatas = CacheManage::getInstance()->setCacheConfig($this->cacheModel)
            ->batchGetCache($ids, function ($ids)
            {
                try
                {
                    // 获取评论信息
                    $datas = $this->where(['id' => ['in', $ids]])
                        ->column('uid,aid,goods,content,is_top,create_time,reply,type,status', 'id');
                    // 获取女神回复ID
                    foreach ($datas as $commentId => $dataItem)
                    {
                        $goddessReplyIds = $this->table('wechatadmin.system_comment_reply')
                            ->where(['comment_id' => $commentId, 'is_goddess' => 1, 'status' => 0])
                            ->order('content_type desc,id desc')->limit(1)->value('id');
                        $datas[$commentId]['goddess_reply_id'] = $goddessReplyIds ?? 0;
                    }
                }
                catch (Exception $e)
                {
                    $datas = [];
                }
                return $datas;
            }, $filed, 'list_details');

        return $commentDatas;
    }

    /**
     * 评论数据重组 获取盖楼信息
     * @param int|null $uid
     * @param array $ids
     * @param array $commentDatas
     * @param int $type 1=>星文，2=>女神动态，3=>女神专区 4=>问答
     * @param int $isOld 是否是新版本 1=>旧版本2.0.0之前 2=>新版本
     * @return array
     * @throws \app\common\lib\exception\ApiException
     * @throws Exception
     */
    public function commentDataReset($uid, array $ids, array $commentDatas, int $type, int $isOld = 2): array
    {
        // 获取所以的评论点赞信息 存在用户未登录情况
        $goods = $uid ? (new ArticleCommentGood())->getGoodFromCache($uid, 1) : [];

        $userIds = [];
        $data = [];
        foreach ($commentDatas as $id => $commentData)
        {
            $userIds[] = $commentData['uid'];
            if ($type === 4)
            {   // 问答
                $data[$id] = [
                    'id' => (int)$id,
                    'content' => htmlspecialchars_decode($commentData['content']),
                    'create_time' => Util::timeToStr($commentData['create_time']),
                    'good_num' => abs($commentData['goods']),
                    'reply_num' => (int)$commentData['reply'],
                    'is_owner' => $uid == $commentData['uid'] ? 1 : 0,
                    'is_good' => in_array($id, $goods, false) ? 1 : 0,
                ];
            } else
            {
                if ($isOld === 2)
                {   // 新版本
                    $data[$id] = [
                        'id' => (int)$id,
                        'content' => htmlspecialchars_decode($commentData['content']),
                        'time' => $isOld === 1 ? (int)$commentData['create_time'] : Util::timeToStr($commentData['create_time']),
                        'good_num' => abs($commentData['goods']),
                        'reply_num' => (int)$commentData['reply'],
                        'is_owner' => $uid == $commentData['uid'] ? 1 : 0,
                        'is_good' => in_array($id, $goods) ? 1 : 0,
                    ];
                } else
                {   // 旧版本
                    $data[$id] = [
                        'id' => (int)$id,
                        'aid' => (int)$commentData['aid'],
                        'content' => htmlspecialchars_decode($commentData['content']),
                        'status' => 0,
                        'create_time' => (int)$commentData['create_time'],
                        'goods' => (int)$commentData['goods'],
                        'reply' => (int)$commentData['reply'],
                        'is_owner' => $uid == $commentData['uid'],
                        'good_status' => in_array($id, $goods),
                    ];
                }
            }
        }

        $userIds = array_filter(array_unique($userIds));
        $userModel = new User();
        // 通过UID批量获取用户头像和昵称信息
        $userInfoList = $userModel->batchGetUserInfo($userIds);
        // 通过UID批量获取用户VIP登记信息
        $userVip = [];
        $userVipModel = new ZlUserVip();
        foreach ($userIds as $uidItem)
        {
            $userVip[$uidItem] = $userVipModel->getUserVipLevel($uidItem);
        }

        // 组合数据 并排序
        $resData = [];
        $configModel = new ConfigManage();
        $replyModel = new ArticleCommentReply();
        $goddessBaseInfoModel = new GoddessBaseInfo();
        $commentGoodModel = new ArticleCommentGood();
        $questionInfo = null;
        $replyGood = null;
        foreach ($ids as $idItem)
        {
            $data[$idItem]['avatar'] = isset($userInfoList[$commentDatas[$idItem]['uid']]) ? $userInfoList[$commentDatas[$idItem]['uid']]['avatar'] ?? '' : '';
            $data[$idItem]['nickname'] = isset($userInfoList[$commentDatas[$idItem]['uid']]) ? $userInfoList[$commentDatas[$idItem]['uid']]['nickname'] ?? '匿名用户' : '匿名用户';
            $data[$idItem]['vip'] = $userVip[$commentDatas[$idItem]['uid']] ?? 0;
            $data[$idItem]['user_type'] = $configModel->innerUser((int)($commentDatas[$idItem]['uid'] ?? 0)); //获取内部官方用户
            // 获取用户当前装扮信息 1=>官方，2=>女神
            $adorn = (new AppUserAdornInfo())->getUserAdornInfo($commentDatas[$idItem]['uid'], $data[$idItem]['user_type']);
            $data[$idItem]['avatar_adorn'] = $adorn['adorn_info']['reality_img'];
            $data[$idItem]['badge'] = array_column($adorn['badge_info'], 'reality_img');
            if ($type === 4)
            {   // 问答
                if ($questionInfo === null)
                {
                    $questionModel = new Zlcr2UserQuestion();
                    $questionInfo = $questionModel->getInfoById($commentDatas[$idItem]['aid'], ['uid']);
                }
                $replyModel->isAnonymity = $this->isAnonymity;
                $data[$idItem]['reply_list'] = $replyModel->getQuestionAnswerLimtData($questionInfo['uid'], (int)$commentDatas[$idItem]['uid'], $uid, $idItem, $userVip); // 盖楼信息
                $data[$idItem]['user_tag'] = $questionInfo['uid'] === (int)$commentDatas[$idItem]['uid'] ? 1 : 0;  // 用户标签 0=>没有  1=>提问者 2=>楼主
                if ($data[$idItem]['user_tag'] === 1 && $this->isAnonymity)
                {//匿名提问
                    $data[$idItem]['avatar'] = $this->anonymityAvatar;
                    $data[$idItem]['nickname'] = $this->anonymityNickname;
                    unset($data[$idItem]['avatar_adorn']);
                    unset($data[$idItem]['badge']);
                }
            } else
            {
                $data[$idItem]['is_top'] = (int)$commentDatas[$idItem]['is_top'];
                if ($type === 5 || $type === 6)
                {
                    if ($questionInfo === null)
                    {
                        $astrCommunityArticleModel = new Zl1AstrCommunityArticle();
                        $questionInfo = $astrCommunityArticleModel->getInfoById($commentDatas[$idItem]['aid'], ['uid']);
                    }
                    $data[$idItem]['reply_list'] = $replyModel->getQuestionAnswerLimtData($questionInfo['uid'], (int)$commentDatas[$idItem]['uid'], $uid, $idItem, $userVip); // 盖楼信息
                } else
                {
                    $data[$idItem]['reply_list'] = $replyModel->getLimtData($idItem); // 盖楼信息
                }
                $goddessReplyData = [];
                if ($isOld === 2)
                {
                    // 获取女神信息
                    $goddessBaseInfo = $goddessBaseInfoModel->getInfo(['nickname', 'avatar']);
                    // 新版本
                    if ($commentDatas[$idItem]['goddess_reply_id'] && $type === 3)
                    {   // 获取女神回复信息
                        $goddessReplyInfo = $replyModel->getInfoById($commentDatas[$idItem]['goddess_reply_id'], ['content_type', 'content', 'good_num', 'duration', 'uid2']);
                        if (is_null($replyGood) && $uid)
                        {
                            $replyGood = $commentGoodModel->getGoodFromCache($uid, 2);
                        }
                        //重组话题的女神回复的结构
                        $themeGoddessReplyData = [
                            'id' => (int)$commentDatas[$idItem]['goddess_reply_id'],
                            'avatar' => $goddessBaseInfo['avatar'],
                            'nickname' => $goddessBaseInfo['nickname'],
                            'content_type' => (int)$goddessReplyInfo['content_type'],
                            'content' => htmlspecialchars_decode($goddessReplyInfo['content']),
                            'good_num' => abs($goddessReplyInfo['good_num']),
                            'duration' => (int)$goddessReplyInfo['duration'],
                            'is_good' => $uid ? (in_array($commentDatas[$idItem]['goddess_reply_id'], $replyGood, false) ? 1 : 0) : 0,
                            'user_type' => 2,//女神账号标识
                            // 新增女神的装扮信息
                            'avatar_adorn' => '',
                            'badge' => [],
                        ];
                        $data[$idItem]['goddess_reply'] = $themeGoddessReplyData; // 女神回复信息
                    } else
                    {
                        //获取当前评论下的所有女神回复id
                        $goddessReplyIds = $replyModel->getGoddessReplyIds($idItem);
                        $goddessReplyIds = array_keys($goddessReplyIds);
                        $goddessReplyInfos = $replyModel->batchGetInfoByIds($goddessReplyIds);
                        if ($goddessReplyInfos)
                        {
                            $goddessReplyInfo = current($goddessReplyInfos);
                            //获取被回复的用户信息
                            $userInfo = current($userModel->batchGetUserInfo([$goddessReplyInfo['uid2']], ['nickname']));
                            foreach ($goddessReplyInfos as $infotem)
                            {
                                $goddessReplyData = [
                                    'id' => $commentDatas[$idItem]['goddess_reply_id'],
                                    'user_type' => 2,
                                    'nickname1' => $goddessBaseInfo['nickname'],
                                    'nickname2' => $userInfo['nickname'] ?: '匿名用户',
                                    'content' => $infotem['content']
                                ];
                                array_unshift($data[$idItem]['reply_list'], $goddessReplyData);
                            }
                        }
                    }
                } else
                {   // 旧版本
                    $data[$idItem]['reply_list'] = $replyModel->getLimtDataOld($idItem); // 盖楼信息
                }
            }

            $resData[] = $data[$idItem];
        }

        return $resData;
    }

    /**
     * 软删除用户当前评论
     * @param int $uid 当前用户id
     * @param int $id 内容ID
     * @param int $c_id 举报ID
     * @param int $type [1=>评论，2=>视频评价，3=》回复]
     * @return bool|string|int
     */
    public function deleteComment(int $uid, int $id, int $c_id, int $type)
    {
        try
        {
            switch ($type)
            {
                case 1://评论
                    $commentModel = new ArticleComment();
                    //获取当前评论内容
                    $info = current($commentModel->batchGetInfo([$id], ['uid', 'aid', 'type']));
                    if ($info)
                    {
                        $commentModel->commentDel($info['uid'], $id);
                    }
                    break;
                case 3://回复
                    $replyModel = new ArticleCommentReply();
                    //获取当前回复内容
                    $info = $replyModel->getInfoById($id, ['uid1', 'comment_id']);
                    $info['uid'] = $info['uid1'];
                    if ($info)
                    {
                        $replyModel->delReply($info['uid'], $id);
                    }
                    break;
                default:
                    return false;
            }
            $reportCommentData = [
                'uid' => $info['uid'],
                'comment_type' => $type,
                'cid' => $id,
                'report_type' => $c_id,
                'status' => 1,
                'admin_uid' => $uid,
                'create_time' => time()
            ];
            // 记录评论自动处理
            (new ZlUserCommentReport())->save($reportCommentData);
        }
        catch (\Exception $e)
        {
            Log::write('api举报，软删除当前评论异常，后台手动处理' . $e->getMessage(), 'error', true);
            return false;
        }
        return $info['uid'];
    }

    /**
     * 删除用户所有文章评论和评论回复
     * @param int $uid 当前用户id
     * @param int $id 内容ID
     * @param int $c_id 举报ID
     * @param int $type [1=>评论，2=>视频评价，3=》回复]
     * @return bool|string|int
     * @throws \Exception
     */
    public function deleteCommentAll(int $uid, int $id, int $c_id, int $type)
    {
        $commentModel = new ArticleComment();
        $areaModel = new GoddessArea();
        $replyModel = new ArticleCommentReply();
        try
        {
            switch ($type)
            {
                case 1://评论
                    //获取当前评论的用户id
                    $info = current($commentModel->batchGetInfo([$id], ['uid']));
                    break;
                case 3://回复
                    //获取当前回复的用户id
                    $info = $replyModel->getInfoById($id, ['uid1']);
                    $info['uid'] = $info['uid1'];
                    break;
                default:
                    return false;
            }
            //获取当前用户所有未删除的评论
            try
            {
                $comments = $commentModel->where(['uid' => $info['uid'], 'status' => 0])->column('id,type,aid');
            }
            catch (\Exception $e)
            {
                $comments = [];
            }
            $article_aids = [];
            $state_aids = [];
            $area_aids = [];
            $user_comment_ids = [];
            $newGoddessReplyIds = [];
            foreach ($comments as $comment)
            {
                switch ($comment['type'])
                {
                    case 1://获取评论星文的评论id
                        $article_aids[$comment['aid']][] = $comment['id'];
                        break;
                    case 2://获取评论动态的评论id
                        $state_aids[$comment['aid']][] = $comment['id'];
                        break;
                    case 3://获取评论话题的评论id
                        $area_aids[$comment['aid']][] = $comment['id'];
                        break;
                }
                $user_comment_ids[] = $comment['id'];
            }
            if ($user_comment_ids)
            {
                //删除当前用户所有评论
                $commentModel->save(['status' => -1], ['id' => ['in', $user_comment_ids]]);
            }
            //星文相关处理
            foreach ($article_aids as $aid => $comment_ids)
            {
                foreach ($comment_ids as $comment_id)
                {
                    //将所属女神回复状态改为删除
                    $goddessReplyIds = $replyModel->getGoddessReplyIds($comment_id);
                    if ($goddessReplyIds)
                    {
                        $newGoddessReplyIds[] = $goddessReplyIds;
                    }
                }
                //更新星文的评论列表信息
                CacheManage::getInstance()->setCacheConfig($commentModel->cacheModel, 1)->setListKeyType($aid)->delJudge($comment_ids, 'list');
            }
            //动态相关处理
            foreach ($state_aids as $aid => $comment_ids)
            {
                foreach ($comment_ids as $comment_id)
                {
                    //将所属女神回复状态改为删除
                    $goddessReplyIds = $replyModel->getGoddessReplyIds($comment_id);
                    if ($goddessReplyIds)
                    {
                        $newGoddessReplyIds[] = $goddessReplyIds;
                    }
                }
                //更新动态的评论列表信息
                CacheManage::getInstance()->setCacheConfig($commentModel->cacheModel, 2)->setListKeyType($aid)->delJudge($comment_ids, 'list');
            }
            //话题相关处理
            foreach ($area_aids as $aid => $comment_ids)
            {
                $area = current($areaModel->batchGetThemeInfo([$aid], ['good_max_comment_id']));
                $isRmCache = false;
                foreach ($comment_ids as $comment_id)
                {
                    //将所属女神回复状态改为删除
                    $goddessReplyIds = $replyModel->getGoddessReplyIds($comment_id);
                    if ($goddessReplyIds)
                    {
                        $newGoddessReplyIds[] = $goddessReplyIds;
                    }
                    //删除话题详情缓存
                    if (isset($area['good_max_comment_id']) && $comment_id == $area['good_max_comment_id'])
                    {
                        $isRmCache = true;
                    }
                }
                //更新话题的评论列表信息并删除话题详情缓存
                CacheManage::getInstance()->setCacheConfig($commentModel->cacheModel, 3)->setListKeyType($aid)->delJudge($comment_ids, 'list');
                if ($isRmCache)
                {
                    CacheManage::getInstance()->setCacheConfig($areaModel->cacheModel, $aid)->rmCache();
                }
            }
            //更新女神回复的状态
            if ($newGoddessReplyIds)
            {
                $replyModel->where(['id' => ['in', $newGoddessReplyIds]])->update(['status' => -1]);
            }

            //获取当前用户所有未删除的回复
            try
            {
                $replys = $replyModel->where(['uid' => $info['uid'], 'status' => 0])->column('id,comment_id,pid');
            }
            catch (\Exception $e)
            {
                $replys = [];
            }
            $comment_ids = [];
            $user_reply_ids = [];
            foreach ($replys as $reply)
            {
                $comment_ids[$reply['comment_id']][] = $reply['id'];
                $user_reply_ids[] = $reply['id'];
            }
            if ($user_reply_ids)
            {
                //删除当前用户所有回复
                $replyModel->save(['status' => -1], ['id' => ['in', $user_reply_ids]]);
            }
            //更新对应评论的回复列表缓存
            foreach ($comment_ids as $comment_id => $reply_ids)
            {
                CacheManage::getInstance()->setCacheConfig(($replyModel->cacheModel), $comment_id)->delJudge($reply_ids, 'list');
            }
            $reportCommentData = [
                'uid' => $info['uid'],
                'comment_type' => $type,
                'cid' => $id,
                'report_type' => $c_id,
                'status' => 1,
                'admin_uid' => $uid,
                'create_time' => time()
            ];
            // 记录评论自动处理
            (new ZlUserCommentReport())->save($reportCommentData);
        }
        catch (\Exception $e)
        {
            Log::write('api举报异常，错误信息：' . $e->getMessage() . '行数：【' . $e->getFile() . $e->getLine() . '】', 'error', true);
            return false;
        }
        return $info['uid'];
    }

    /**
     * 获取 问答 讨论回复 + 点赞最多的 3条
     * @param string $aid 问答问题ID
     * @param int $type 1=>星文，2=>女神动态，3=>女神专区 4=>问答
     * @return array
     * @throws Exception
     */
    public function getCommentAndGoodMaxLimit($aid, int $type = 4)
    {
        $pageData = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, 'question_answer_' . $aid)
            ->setPage(1)
            ->setPageSize(3)
            ->setSort('desc')
            ->setListKeyType('comment_good')// 评论和回复最多的
            ->getListPageDataIds(function ($ids = [], $isCache = true, $sortType = 'desc') use ($aid, $type)
            {
                try
                {
                    $data = $this->where(['aid' => $aid, 'type' => $type, 'status' => 0])->order('sort desc,id desc')->column('reply,goods,`reply`+`goods` as sort', 'id');

                    $resData = [];
                    foreach ($data as $id => $datum)
                    {
                        if ($datum['sort'] > 0)
                        {
                            $resData[$id] = $datum;
                        }
                    }
                    return $resData;
                }
                catch (\Exception $e)
                {
                    return [];
                }
            }, 'sort', 0);

        return $pageData['data'] ? array_keys($pageData['data']) : [];
    }

    /**
     * 设置 问答 讨论 回复+点赞 的排序值
     * @param $aid
     * @param int $commentId
     * @param int $sort
     * @throws Exception
     */
    public function setCommentAndGoodSum($aid, int $commentId, int $sort)
    {
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, 'question_answer_' . $aid)->listAdd([$commentId => $sort], 'comment_good');
    }

    /**
     * 获取提问者发布的最新的一个讨论ID
     * @param $aid
     * @param int $type 类型 1=>星文评论，2=>女神动态评论，3=>女神专区评论 4=>问答评论
     * @param int $uid 问答提问者用户ID
     * @param int $limit 获取ID数量
     * @return array
     */
    public function getQuestionAnswerRecommentId($aid, int $type, int $uid, int $limit)
    {
        $cacheKey = 'content_comment:recomment_' . $type . ':' . $aid;
        $ids = Cache::get($cacheKey, false);

        if ($ids === false)
        {
            $ids = $this->where(['aid' => $aid, 'uid' => $uid, 'type' => $type, 'status' => 0])->order('id desc')->column('id');

            Cache::set($cacheKey, $ids, 600);
        }

        if (count($ids) < $limit)
        {
            return $ids;
        } else
        {
            return array_slice($ids, 0, $limit);
        }
    }

    /**
     * 删除问题提问者发布的讨论缓存
     * @param $aid
     * @param int $type
     */
    public function delQuestionAnswerRecommentIdCache($aid, int $type)
    {
        $cacheKey = 'content_comment:recomment_' . $type . ':' . $aid;

        Cache::rm($cacheKey);
    }
}
